﻿using System;
using System.Linq;
using RpcClient;
using RpcHelper;
using Wedonek.RpcStore.Gateway.Interface;
using Wedonek.RpcStore.Gateway.Model;
using Wedonek.RpcStore.Service.Interface;
using Wedonek.RpcStore.Service.Model;

namespace Wedonek.RpcStore.Gateway.Service
{
        internal class TraceLogService : ITraceLogService
        {
                private readonly ITraceLogCollect _Trace;
                private readonly IServerTypeCollect _ServerType;
                private readonly IServerRegionCollect _ServerRegion;
                private readonly IServerCollect _Server;
                public TraceLogService (ITraceLogCollect trace,
                        IServerTypeCollect serverType,
                        IServerCollect server,
                        IServerRegionCollect region)
                {
                        this._Server = server;
                        this._ServerRegion = region;
                        this._ServerType = serverType;
                        this._Trace = trace;
                }
                public TraceLogDetailed Get (Guid id)
                {
                        return this._Trace.Get (id);
                }
                public TraceLog[] Gets (string traceId)
                {
                        RpcTraceLog[] list = this._Trace.Gets (traceId);
                        if (list.Length == 0)
                        {
                                return null;
                        }
                        BasicServerType[] types = this._ServerType.GetBasic (list.Distinct (a => a.SystemTypeId));
                        ServerRegion[] regions = this._ServerRegion.Gets (list.Distinct (a => a.RegionId));
                        BasicService[] services = this._Server.GetBasic (list.Distinct (a => a.RemoteId != 0, a => a.RemoteId));
                        return list.ConvertMap<RpcTraceLog, TraceLog> ((a, b) =>
                        {
                                b.SystemType = types.Find (c => c.Id == a.SystemTypeId, c => c.SystemName);
                                b.Region = regions.Find (c => c.Id == a.RegionId, c => c.RegionName);
                                if (b.RemoteId != 0)
                                {
                                        b.Remote = services.Find (c => c.Id == a.RemoteId, c => c.ServerName);
                                }
                                return b;
                        });
                }
        }
}
